import { login, getInfo, getMyMenuTree } from '@/api/user'; // logout,
import { getToken, setToken, removeToken } from '@/utils/auth';
import { resetRouter, constantRoutes } from '@/router';
import router from '@/router';
import routeMap from '@/router/component.js';

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '', // 用户名称
    avatar: '', // 用户头像
    newRoutes: []
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROUTER: (state, routes) => {
    state.newRoutes = routes;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password })
        .then(({ data, resultCode }) => {
          if (resultCode === '0000') {
            commit('SET_TOKEN', data.token);
            commit('SET_NAME', username);
            sessionStorage.setItem('userId', username);
            setToken(data.token);
            resolve(data);
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response;
          if (!data) {
            return reject('验证失败，请重新登录.');
          }
          const { name, avatar } = data;

          commit('SET_NAME', name);
          commit('SET_AVATAR', avatar);
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken(); // must remove  token  first
      resetRouter();
      commit('RESET_STATE');
      resolve();
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit('RESET_STATE');
      resolve();
    });
  },

  getNewRouter({ commit }) {
    return new Promise((resolve, reject) => {
      // 请求接口获取路由权限数据
      getMyMenuTree()
        .then(({ data = undefined } = {}) => {
          if (data) {
            // 格式化路由函数
            const formatRoutes = (routes = [], routeData) => {
              const routeTotalData = [];
              if (Array.isArray(routes) && routes.length) {
                routes.forEach(route => {
                  if (Array.isArray(route.children) && route.children.length) {
                    route.redirect = route.children[0].path;
                  }
                  if (route.component) {
                    route.component = routeMap[route.component];
                    if (!routeData) {
                      routeTotalData.push(route);
                    }
                  }
                  if (route.children && route.children.length) {
                    formatRoutes(route.children, route);
                  }
                });
              }
              return routeTotalData;
            };
            const finalRoutes = [
              ...formatRoutes(data),
              { path: '*', redirect: '/404' }
            ];
            router.addRoutes(finalRoutes); // 追加路由
            commit('SET_ROUTER', finalRoutes); // 存储路由数据
            // console.log(finalRoutes);
            resolve(finalRoutes);
          } else {
            commit('SET_ROUTER', []); // 存储路由数据
            resolve([]);
          }
        })
        .catch(err => {
          console.log('getMyMenuTree-err:', err);
          reject(err);
        });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
